package gamagora.game.animations
{
	import gamagora.game.utils.OSImages;
	
	import org.flixel.FlxG;
	import org.flixel.FlxSprite;
	
	public class OSMonkeyCage extends OSAnimation
	{
		private static const TIME_BEFORE_MOVE:Number = 5;
		
		private var _monkeys:Vector.<OSMonkey>;
		private var _nbMonkeys:uint;
		private var _leftBound:Number;
		private var _rightBound:Number;
		private var _moveTimer:Number;
		private var _halfWidth:Number;
		private var _startX:Number;
		
		//TODO prévoir une version premier plan avec collision (juste un gros bloc) ?
		public function OSMonkeyCage(X:Number=0, Y:Number=0)
		{
			super(X, Y, OSAnimation.BACKGROUND3, OSImages.CAGE);
			_startX = X;
			_leftBound = x + 40;
			_rightBound = x + width + 16;
			offset.x = -width / 2;
		
			_halfWidth = (_rightBound - _leftBound) / 2;
			
			_monkeys = new Vector.<OSMonkey>();
			_monkeys.push(new OSMonkey(_leftBound + 30, y + 16, OSAnimation.BACKGROUND3));
			_monkeys.push(new OSMonkey(_leftBound + 60, y + 16, OSAnimation.BACKGROUND3));
			
			_nbMonkeys = _monkeys.length;
			
			_moveTimer = 0;
		}
		
		public override function update():void
		{
			super.update();
			
			for(var i:uint=0;i<_nbMonkeys;i++)
			{
				_monkeys[i].update();
				_monkeys[i].postUpdate();
			}
			
			_moveTimer += FlxG.elapsed;
			if(_moveTimer >= TIME_BEFORE_MOVE)
			{
				_moveTimer = 0;
				
				for(i=0;i<_nbMonkeys;i++)
				{
					if(!_monkeys[i].move) //Hey ho je bouge déjà, ca va hein !
					{
						if(uint(Math.random() * 2) == 0) // On bouge ?
						{
							if(_monkeys[i].x > _leftBound + _halfWidth) // Il y a plus de place a gauche
							{
								_monkeys[i].moveTo(_monkeys[i].x - _halfWidth);
							}
							else //Finalement à droite c'est mieux
							{
								_monkeys[i].moveTo(_monkeys[i].x + _halfWidth);
							}
						}
					}
				}
				
			}
		}

		public override function draw():void
		{
			for(var i:uint=0;i<_nbMonkeys;i++)
			{
				var sx:Number = _monkeys[i].x;
				_monkeys[i].x += (x - _startX);
				_monkeys[i].draw();
				_monkeys[i].x = sx;
			}
			
			super.draw();
		}
		
		public override function destroy():void
		{
			super.destroy();
			for(var i:uint=0;i<_nbMonkeys;i++)
			{
				_monkeys[i].destroy();
			}
		}
	}
}
